package com.yingdong.logic.service;

import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.logging.LogManager;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.yingdong.annotation.AutoInvoke;

import com.yingdong.logic.domain.GameUser;
import com.yingdong.logic.domain.QueueLoginInfo;
import com.yingdong.sceneserver.net.GameUserSession;
import com.yingdong.sceneserver.opcode.Dispatcher;

@Service
public class OnlineService {
	static Log logger = LogFactory.getLog(OnlineService.class);
	public static BlockingQueue<QueueLoginInfo> loginQueue = new LinkedBlockingQueue<>();
	private static Map<Integer, GameUser> onlineUserMap = new ConcurrentHashMap<>();

	@AutoInvoke
	public static void init() {

	}

	public static int getOnlineNum() {
		return onlineUserMap.size();
	}

	public static GameUser getGameUserByAccId(int accId) {
		for (GameUser gameUser : onlineUserMap.values()) {
			if (gameUser.getUsr().getAccId() == accId) {
				return gameUser;
			}
		}
		return null;
	}

	public static void putOline(GameUser user) {
		onlineUserMap.put(user.getUserId(), user);
	}

	public static void removeOnline(int userId) {
		onlineUserMap.remove(userId);
	}

	public static GameUser getOnlineGameUser(int userId) {
		return onlineUserMap.get(userId);
	}

	public static boolean isOnline(int userId) {
		return onlineUserMap.containsKey(userId);
	}

	public static GameUser getGameUserInSession(GameUserSession session) {
		if (session.getContext().containsKey("gamePlayer"))
			return (GameUser) session.getContext().get("gamePlayer");
		return null;
	}

	public static void clearGameUserSession(GameUserSession session) {
		Dispatcher.sessionMap.remove(session.getSessionId());
		session.getContext().clear();
		session.setSessionId(-1);

	}

	public static void save() {
		for (GameUser gameUser : onlineUserMap.values()) {
			gameUser.saveToDb();
		}
		logger.info("所有" + onlineUserMap.size() + "名玩家存储完毕");
	}

	public static void update(int dt) {
		for (GameUser gameUser : onlineUserMap.values()) {
			gameUser.onUpdate(dt);
		}
	}
}
